package com.lzx.adx.report.support.strategy.v3.media;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.CallTypeMappingDTO;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.support.strategy.v2.media.AbstractCallback;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.WANG_YI)
public class WangYiChannel extends AbstractChannel {
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, OcpxAccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        Map<String, CallTypeMappingDTO> callTypeMap = getCallTypeMap(accountDTO);
        CallTypeMappingDTO callTypeMappingDTO = callTypeMap.get(callType);
        String eventType=callTypeMappingDTO.getMediaReturnType();

        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        log.info("账号为{} 请求id为{}网易转码地址为：{}",reportDTO.getDspId(), reportDTO.getBizRequestId(), decodeUrl);
        //拼接完整的请求参数
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("conv_type", eventType);
        paramsReq.put("t", ts);
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("账号为{} 请求id为{}上报网易完整地址为：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("账号为{} 请求id为{}上报网易转换响应的结果为{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);


        accountDTO.setFinalURL(finalUrl);
        accountDTO.setBody(result);
        return ResponseEntity.ok(new Result());
    }
}
